<html>

<head>
    <script src="build/pdf.js"></script>
    <style>
        #the-canvas {
            border: 1px solid black;
            direction: ltr;
            position: absolute;
            left: 0px;
            top: 0px;
        }

        [hidden] {
            display: none !important;
        }

        #pointer {
            position: absolute;
            /* border-radius: 50%; */
            /* background-color: #f00; */
            /* opacity: 0.9; */
            display: none;
            width: 60px;
            height: 60px;
        }

        body {
            overflow: hidden;
            position: absolute;
            left: 0px;
            top: 0px;
            margin: 0px;
        }
    </style>
    <script src="ws-audio-api/dist/ws-audio-api.min.js"></script>
</head>

<body>
    <!-- <div>
        <button id="prev">Previous</button>
        <button id="next">Next</button>
        &nbsp; &nbsp;
        <span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
    </div> -->
    <svg id="pointer">
        <circle cx=30 cy=30 r=29 fill=#00f stroke=none opacity=0.1></circle>
        <circle cx=30 cy=30 r=5 fill=#00f stroke=none opacity=0.8></circle>
        <circle cx=30 cy=30 r=28 fill=none stroke=#00f stroke-width=3px opacity=0.8></circle>
    </svg>
    </div>
    <canvas id="pdf-canvas"></canvas>

    <script>
        var pdfjsLib = window['pdfjs-dist/build/pdf'];
        function getws(query){
            proto = window.location.protocol.replace("http", "ws") + "//"
            url = proto + window.location.host + query;
            return new WebSocket(url);
        }
        var ws = getws("/echo");
        var pointer = document.getElementById("pointer");
        var channel = document.location.href.split("viewer.html?")[1];
        var channel_init = {
            type: "subscribe",
            name: channel,
        }
        ws.addEventListener("open", () => { ws.send(JSON.stringify(channel_init)); })
        // The workerSrc property shall be specified.
        //pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';

        var pdfDoc = null,
            pageNum = 1,
            pageRendering = false,
            pageNumPending = null,
            canvas = document.getElementById('pdf-canvas'),
            ctx = canvas.getContext('2d');
        var streamer, player;
        var viewport = null;
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        var cursor_hide_timeout = 3000;
        var cursor_hide_timer = null;
        function show_cursor(truth) {
            if (truth) {
                document.getElementById("pointer").style.display = "block";
            } else {
                document.getElementById("pointer").style.display = "none";
            }
        }
        ws.addEventListener("message", function (e) {
            var ev = JSON.parse(e.data);
            console.log(ev);
            if (ev.type == "page") {
                queueRenderPage(parseInt(ev.page));
            } else if (ev.type == "mousemove") {
                // console.log(ev.x, ev.y);
                function render() {
                    if (viewport === null) return;
                    if (cursor_hide_timer) {
                        clearTimeout(cursor_hide_timer);
                    }
                    show_cursor(1);
                    pointer.style.left = ev.x * viewport.width - 30 + "px";
                    pointer.style.top = ev.y * viewport.height - 30 + "px";
                    // canvas.getContext('2d').fillRect(ev.x * canvas.width, ev.y * canvas.height, 10, 10);
                    cursor_hide_timer = setTimeout(() => { show_cursor(0); cursor_hide_timer = null; }, cursor_hide_timeout);
                }


                requestAnimationFrame(render);

                // console.log(pointer.style.left);
                // console.log(pointer.style.top);
            } else if (ev.type == "viewer-mute") {
                console.log(ev);
                if (ev.stat) {
                    streamer.stop();
                } else {
                    streamer.start();
                }
            } else if (ev.type == "channel_info") {
                pdfjsLib.getDocument(ev.url).promise.then(function (pdfDoc_) {
                    pdfDoc = pdfDoc_;
                    pageNum = parseInt(ev.page);
                    console.log(ev.page);
                    renderPage(pageNum);
                });
                var query = {
                    "mode": "play",
                    "channel": channel,
                    "client_id": ev.client_id
                }
                var ws = getws("/echos?" + new URLSearchParams(query).toString());
                player = new WSAudioAPI.Player({}, ws);
                player.start();
                var query = {
                    "mode": "stream",
                    "channel": channel,
                    "client_id": ev.client_id
                }
                var ws = getws("/echos?" + new URLSearchParams(query).toString());
                streamer = new WSAudioAPI.Streamer({}, ws);
                if (!ev.mute){
                  console.log("mute:", ev.mute);
                  streamer.start();
                }
            }
        });
        /**
         * Get page info from document, resize canvas accordingly, and render page.
         * @param num Page number.
         */
        function renderPage(num) {
            pageRendering = true;
            // Using promise to fetch the page
            pdfDoc.getPage(num).then(function (page) {
                viewport = page.getViewport({ scale: 1 });
                var bufcan = document.createElement("canvas");

                bufcan.width = window.innerWidth;
                bufcan.height = window.innerHeight;

                var scale = bufcan.width / viewport.width * 2;
                // console.log(bufcan.width, viewport.width);
                viewport = page.getViewport({ scale: scale });
                // console.log(bufcan.width, viewport.width);
                bufctx = bufcan.getContext('2d');
                if (canvas.width != bufcan.width || canvas.height != bufcan.height) {
                    // console.log(canvas.width, canvas.height, bufcan.width, bufcan.height);
                    canvas.width = bufcan.width;
                    canvas.height = bufcan.height;
                    // console.log(canvas.width, canvas.height);
                }
                // Render PDF page into canvas context
                var renderContext = {
                    canvasContext: bufctx,
                    viewport: viewport
                };
                var renderTask = page.render(renderContext);

                // Wait for rendering to finish
                renderTask.promise.then(function () {
                    ctx.drawImage(bufcan, 0, 0);
                    pageRendering = false;
                    if (pageNumPending !== null) {
                        // New page rendering is pending
                        renderPage(pageNumPending);
                        pageNumPending = null;
                    }
                });
            });

        }

        /**
         * If another page rendering in progress, waits until the rendering is
         * finised. Otherwise, executes rendering immediately.
         */
        function queueRenderPage(num) {
            if (pageRendering) {
                pageNumPending = num;
            } else {
                renderPage(num);
            }
        }

        /**
         * Asynchronously downloads PDF.
         */


    </script>
</body>

</html>